package com.wondertek.poms.service.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wondertek.poms.common.utils.StringUtil;
import com.wondertek.poms.common.vo.GlobalCodeEnum;
import com.wondertek.poms.common.vo.PageBean;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.core.config.UrlConfig;
import com.wondertek.poms.core.service.IBcLogService;
import com.wondertek.poms.core.service.IContentBaseFeeService;
import com.wondertek.poms.core.service.IMoveContLogService;
import com.wondertek.poms.core.service.IPrdContService;
import com.wondertek.poms.dao.po.EmergencyBcLog;
import com.wondertek.poms.dao.po.MoveContLog;
import com.wondertek.poms.dao.pojo.BcProcessLogPojo;
import com.wondertek.poms.dao.pojo.BcRecodePojo;
import com.wondertek.poms.dao.pojo.ContentPojo;
import com.wondertek.poms.dao.pojo.ProgramPojo;
import com.wondertek.poms.dao.repo.IEmergencyBcLogDao;
import com.wondertek.poms.service.vo.BcProcessLogVo;
import com.wondertek.poms.service.vo.BcRecodeVo;
import com.wondertek.poms.service.vo.EmergencyBcLogVo;
import com.wondertek.poms.service.vo.ProgramVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @ClassName: HistoryRecordControl
 * @Description: TODO
 * @Author MrYuan
 * @Date: 2021/1/26 14:41
 * @Version 1.0
 */
@Api(value = "历史记录", tags = "历史记录")
@RestController
@Slf4j
@RequestMapping("/history-record")
public class HistoryRecordControl {
    @Autowired
    IBcLogService bcLogService;
    @Resource
    private RestTemplate restTemplateOut;
    @Autowired
    private UrlConfig urlConfig;
    @Autowired
    IMoveContLogService moveContLogService;
    @Autowired
    IPrdContService prdContService;
    @Autowired
    private IContentBaseFeeService contentBaseFeeService;
    @Autowired
    IEmergencyBcLogDao emergencyBcLogDao;
//    @Autowired
//    ICdiPlayUrlLogDao cdiPlayUrlLogDao;
//    @Autowired
//    ICdiPlayUrlLogService cdiPlayUrlLogService;
//    @Autowired
//    IExportContentDao exportContentDao;

    @ApiOperation(value = "播控历史列表", notes = "播控历史列表")
    @PostMapping(value = "/bc-history-list")
    public ResultBean bcHistory(
            @RequestBody(required = false) BcRecodeVo bcRecodeVo,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int rows,
            @RequestParam(defaultValue = "b.BC_LOG_ID") String sidx,
            @RequestParam(defaultValue = "desc") String sord) {
        BcRecodePojo bcRecodePojo = new BcRecodePojo();
        BeanUtils.copyProperties(bcRecodeVo, bcRecodePojo);
        Page<BcRecodePojo> pages = bcLogService.findAll(bcRecodePojo, page, rows, sidx, sord);
        if (CollectionUtils.isEmpty(pages.getContent())) {
            return ResultBean.error("输入不正确的值");
        }
        return PageBean.ok(pages.getTotalPages(), pages.getTotalElements(), pages.getContent());
    }

    @ApiOperation(value = "播控流程日志列表", notes = "播控流程日志列表")
    @PostMapping(value = "/bc-process")
    public ResultBean bcpPocess(
            @RequestBody(required = false) BcProcessLogVo bcProcessLogVo,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int rows,
            @RequestParam(defaultValue = "t.GET_TIME") String sidx,
            @RequestParam(defaultValue = "desc") String sord) {
        BcProcessLogPojo bcProcessLogPojo = new BcProcessLogPojo();
        BeanUtils.copyProperties(bcProcessLogVo, bcProcessLogPojo);
        Page<BcProcessLogPojo> pages = bcLogService.findAll(bcProcessLogPojo, page, rows, sidx, sord);
        if (CollectionUtils.isEmpty(pages.getContent())) {
            return ResultBean.error("输入不正确的值");
        }
        return PageBean.ok(pages.getTotalPages(), pages.getTotalElements(), pages.getContent());
    }

    @ApiOperation(value = "节目发布")
    @GetMapping("/note-publish")
    public ResultBean notePublish(String prdContIds, String type) {
        if (StringUtils.isBlank(prdContIds)) {
            return ResultBean.error("prdContIds不能为空");
        }
        try {
            log.info("url:" + urlConfig.getOnlineUrl() + ";prdContIds=" + prdContIds + ";type=" + type);
            ResponseEntity<String> responseEntity = restTemplateOut
                    .getForEntity(urlConfig.getOnlineUrl() + "?prdContIds=" + prdContIds + "&type=" + type, String.class);
            String result = responseEntity.getBody();
            JSONObject json = JSON.parseObject(result);
            if ("true".equals(StringUtil.nullToString(json.get("success")))) {
                return new ResultBean(GlobalCodeEnum.SUCCESS.getCode(), "调用成功,请等待后台处理");
            } else {
                log.error(StringUtil.nullToString(json.get("message")));
                return ResultBean.error(StringUtil.nullToString(json.get("message")));
            }
        } catch (Exception e) {
            log.error(e.toString());
            return ResultBean.error(e.toString());
        }
    }

    @ApiOperation(value = "节目发布记录列表")
    @PostMapping("/note-list")
    public ResultBean notePublishList(
            @RequestBody(required = false) ProgramVo programVo,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int rows,
            @RequestParam(defaultValue = "PUB_TIME") String sidx,
            @RequestParam(defaultValue = "desc") String sord) {
        ProgramPojo programPojo = new ProgramPojo();
        BeanUtils.copyProperties(programVo, programPojo);
        Page<ProgramPojo> pages = prdContService.findAll(programPojo, page, rows, sidx, sord);
        if (CollectionUtils.isEmpty(pages.getContent())) {
            return ResultBean.error("输入不正确的值");
        }
        return PageBean.ok(pages.getTotalPages(), pages.getTotalElements(), pages.getContent());
    }

    @ApiOperation(value = "节目状态信息列表")
    @PostMapping("/note-status-list")
    public ResultBean noteStatusList(
            @RequestBody(required = false) ProgramVo programVo,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int rows,
            @RequestParam(defaultValue = "PUB_TIME") String sidx,
            @RequestParam(defaultValue = "desc") String sord) {
        ProgramPojo programPojo = new ProgramPojo();
        BeanUtils.copyProperties(programVo, programPojo);
        Page<ProgramPojo> pages = prdContService.findAll(programPojo, page, rows, sidx, sord);
        if (CollectionUtils.isEmpty(pages.getContent())) {
            return ResultBean.error("输入不正确的值");
        }
        return PageBean.ok(pages.getTotalPages(), pages.getTotalElements(), pages.getContent());
    }

    @ApiOperation(value = "节目移包信息导出")
    @GetMapping("/note-move-export")
    public void export(HttpServletRequest request, HttpServletResponse response,
                       MoveContLog moveContLog,
                       @RequestParam(defaultValue = "1") int page,
                       @RequestParam(defaultValue = "20") int rows,
                       @RequestParam(defaultValue = "pm.create_time") String sidx,
                       @RequestParam(defaultValue = "desc") String sord) throws IOException {


        Page<MoveContLog> pages = moveContLogService
                .findMoveLogList(moveContLog, page, rows, sord, sidx);
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("节目移包记录", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), MoveContLog.class).sheet("移包记录表一").doWrite(pages.getContent());
    }

    @ApiOperation(value = "节目移包信息列表")
    @PostMapping("/note-move-list")
    public ResultBean list(HttpServletRequest request,
                           MoveContLog moveContLog,
                           @RequestParam(defaultValue = "1") int page,
                           @RequestParam(defaultValue = "20") int rows,
                           @RequestParam(defaultValue = "pm.create_time") String sidx,
                           @RequestParam(defaultValue = "desc") String sord) {
        Page<MoveContLog> pages = moveContLogService
                .findMoveLogList(moveContLog, page, rows, sord, sidx);
        return PageBean.ok(pages.getTotalPages(), pages.getTotalElements(), pages.getContent());
    }

    @ApiOperation(value = "节目计费配置记录列表")
    @GetMapping("/config-fee")
    public ResultBean configFee(String prdContIds) {
        return ResultBean.ok(contentBaseFeeService.getContentBaseFeeList(prdContIds));
    }

//    @ApiOperation(value = "一键叫审日志列表")
//    @PostMapping("/onekey-trail")
//    public ResultBean oneKeyTrail(
//            @RequestBody(required = false) EmergencyBcLogVo emergencyBcLog,
//            @RequestParam(defaultValue = "1") int page,
//            @RequestParam(defaultValue = "20") int rows,
//            @RequestParam(defaultValue = "CREATE_TIME") String sidx,
//            @RequestParam(defaultValue = "desc") String sord
//    ) {
//        Page<EmergencyBcLog> pages = prdContService.findAll(emergencyBcLog, page, rows, sidx, sord);
//        return PageBean.ok(pages.getTotalPages(), pages.getTotalElements(), pages.getContent());
//    }

//    @ApiOperation(value = "魔百盒日志列表")
//    @PostMapping("/cdiloglist")
//    public ResultBean cdiLogList(
//            @RequestBody(required = false) CdiPlayUrlLogVo cdi,
//            @RequestParam(defaultValue = "1") int page,
//            @RequestParam(defaultValue = "20") int rows,
//            @RequestParam(defaultValue = "CREATE_DATE") String sidx,
//            @RequestParam(defaultValue = "desc") String sord) {
//
//        Page<CdiPlayUrlLog> pages = cdiPlayUrlLogService.findAll(cdi, page, rows, sidx, sord);
//        return PageBean.ok(pages.getTotalPages(), pages.getTotalElements(), pages.getContent());
//    }
//
//    @ApiOperation(value = "导出发布清单列表")
//    @PostMapping("/exportContentList")
//    public ResultBean getExportContentList(
//            @RequestParam(defaultValue = "1") int page,
//            @RequestParam(defaultValue = "2") int rows,
//            @RequestParam(defaultValue = "id") String sidx,
//            @RequestParam(defaultValue = "desc") String sord
//    ) {
//        new Sort(Sort.Direction.DESC, "id");
//        Page<ExportContent> pages = exportContentDao.findAll(new Specification<ExportContent>() {
//            @Override
//            public Predicate toPredicate(Root<ExportContent> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
//                Path<Object> del = root.get("del");
//                Path<Object> status = root.get("status");
//                Predicate p1 = cb.equal(del, "0");
//                Predicate p2 = cb.equal(status, "2");
//                Predicate select = cb.and(p1, p2);
//                return select;
//            }
//        }, getPageable(page, rows, sidx, sord));
//        System.out.println(pages.getContent());
//
////        return PageBean.ok(pages.getTotalPages(), pages.getTotalElements(), pages.getContent());
//        return PageBean.ok( pages.getContent());
//    }
//
//    protected Pageable getPageable(int page, int rows, String column, String order) {
//        Sort sort = new Sort("desc".toLowerCase().equals(order) ?
//                Sort.Direction.DESC : Sort.Direction.ASC, column);
//        Pageable pageable = PageRequest.of(page, rows, sort);
//        return pageable;
//    }
///*
//    @ApiOperation(value = "导出发布清单列表下载")
//    @GetMapping("/")
//    public void gfas() {
//    }
//
//    @ApiOperation(value = "导出发布清单列表删除")
//    @GetMapping("/")
//    public void gsfa() {
//    }
//    }*/
}